package com.proton.carepatchtemp.utils.net;

import android.text.TextUtils;

import com.android.volley.Response;
import com.apkfuns.logutils.LogUtils;
import com.proton.carepatchtemp.application.VCare;
import com.proton.carepatchtemp.constant.Codes;
import com.proton.carepatchtemp.constant.Extras;
import com.proton.carepatchtemp.constant.Settings;
import com.proton.carepatchtemp.database.SpAssist;
import com.proton.carepatchtemp.database.dao.AssistInfo;
import com.proton.carepatchtemp.database.dao.RegisterInfo;
import com.proton.carepatchtemp.database.dao.SignActvts;
import com.proton.carepatchtemp.database.table.FestivalSplash;
import com.proton.carepatchtemp.database.table.User;
import com.proton.carepatchtemp.utils.JSONUtils;
import com.proton.carepatchtemp.utils.UmengUtils;
import com.proton.carepatchtemp.utils.eventbus.MainEvent;
import com.proton.carepatchtemp.utils.net.pair.ParamPair;
import com.proton.carepatchtemp.utils.net.pair.ResultPair;
import com.proton.carepatchtemp.utils.net.request.JGet;
import com.proton.carepatchtemp.utils.net.request.JPost;
import com.tencent.bugly.crashreport.CrashReport;

import org.apache.commons.codec.binary.Base64;
import org.greenrobot.eventbus.EventBus;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;


/**
 * Created by Api on 2016/9/21.
 */

public class SignCenter extends DataCenter {
    public static final String register = "/sign/register";
    public static final String login = "/sign/login";
    public static final String googleLogin = "/sign/googleLogin";
    public static final String facebookLogin = "/sign/faceBookLogin";
    public static final String getRegCap = "/sign/sendregistercaptcha";
    public static final String valiRegCap = "/sign/validateregistercaptcha";
    public static final String getFpwdCap = "/sign/sendforgetpwcaptcha";
    public static final String valiFpwdCap = "/sign/validateforgetpwcaptcha";
    public static final String changeFpwd = "/sign/changeforgetpw";
    public static final String setumtoken = "/user/setumtoken";
    public static final String Splash = "/free/specialFestivals";

    public static boolean getSplashPic() {
        if (DataCenter.noNet()) {
            return false;
        }
        List params = new ArrayList<>();
        VolleyUtil.addRequest(new JGet(getApi(Splash), params, new Response.Listener<ResultPair>() {

            @Override
            public void onResponse(ResultPair response) {
                String ret = response.getName();
                String msg = response.getValue();
                if (response.isSuccess()) {
                    FestivalSplash splash = JSONUtils.getObj(msg, FestivalSplash.class);
                    EventBus.getDefault().post(new MainEvent(Codes.NET_GET_SPLASH_PIC, splash));
                }
                LogUtils.d(response);
            }
        }));
        return false;
    }

    public static boolean loginFacebook(final String email, final String id, String tokenString) {
        List<ParamPair> params = new ArrayList<>();
        params.add(new ParamPair("email", email));
        params.add(new ParamPair("userId", id));
        params.add(new ParamPair("tokenString", tokenString));
        VolleyUtil.addRequest(new JPost(getApi(facebookLogin), params, new Response.Listener<ResultPair>() {

            @Override
            public void onResponse(ResultPair response) {
                String ret = response.getName();
                String msg = response.getValue();
                LogUtils.d(response);
                if (RET_S.equalsIgnoreCase(ret)) {
                    String apiStr = JSONUtils.getString(msg, Extras.APITOKEN);
                    User user = new User();
                    user.setId(Long.parseLong(JSONUtils.getString(msg, Extras.UID)));
                    user.setApiToken(apiStr);
                    LogUtils.e("userId = " + user.getId());
                    VCare.get().setupSessionCookie(apiStr, apiStr, user, msg);
                    //友盟推送初始化
                    if (!TextUtils.isEmpty(UmengUtils.getdeviceToken())) {
                        setUmtoken(UmengUtils.getdeviceToken());
                    }
//                    SpAssist.setAssistInfo(assistInfo);
                    XMPPCenter.loginChat();
                    CrashReport.setUserId("facebook:" + user.getId());
                }
                int codeId = Codes.NET_SIGN_LOGIN;
                EventBus.getDefault().post(new MainEvent(codeId, ret, msg));
            }
        }));
        return false;
    }

    public static boolean loginGoogle(final String email, final String id, String idToken) {
        if (DataCenter.noNet()) {
            return false;
        }

        List<ParamPair> params = new ArrayList<>();
        params.add(new ParamPair("email", email));
        params.add(new ParamPair("userId", id));
        params.add(new ParamPair("idToken", idToken));
        VolleyUtil.addRequest(new JPost(getApi(googleLogin), params, new Response.Listener<ResultPair>() {

            @Override
            public void onResponse(ResultPair response) {
                String ret = response.getName();
                String msg = response.getValue();
                LogUtils.d(response);
                if (RET_S.equalsIgnoreCase(ret)) {
                    String apiStr = JSONUtils.getString(msg, Extras.APITOKEN);
                    User user = new User();
                    user.setId(Long.parseLong(JSONUtils.getString(msg, Extras.UID)));
                    user.setApiToken(apiStr);
                    LogUtils.e("userId = " + user.getId());
                    VCare.get().setupSessionCookie(apiStr, apiStr, user, msg);
                    //友盟推送初始化
                    if (!TextUtils.isEmpty(UmengUtils.getdeviceToken())) {
                        setUmtoken(UmengUtils.getdeviceToken());
                    }
                    CrashReport.setUserId("facebook:" + user.getId());
                    XMPPCenter.loginChat();
                } else {

                }
                int codeId = Codes.NET_SIGN_LOGIN;
                EventBus.getDefault().post(new MainEvent(codeId, ret, msg));
            }
        }));
        return false;
    }

    public static boolean login(final RegisterInfo info, final int name) {
        if (DataCenter.noNet()) {
            return false;
        }
        List params = new ArrayList<>();
        params.add(new ParamPair(Extras.TYPE, info.getType()));
        params.add(new ParamPair(Extras.MOBILE, info.getMobile()));
        params.add(new ParamPair(Extras.PWD, md5(info.getPwd())));
        VolleyUtil.addRequest(new JPost(getApi(login), params, new Response.Listener<ResultPair>() {

            @Override
            public void onResponse(ResultPair response) {
                String ret = response.getName();
                String msg = response.getValue();
                if (RET_S.equalsIgnoreCase(ret)) {
                    String apiStr = JSONUtils.getString(msg, Extras.APITOKEN);
                    String userStr = JSONUtils.getString(msg, Extras.USER);
                    User user = JSONUtils.getObj(userStr, User.class);
                    user.setApiToken(apiStr);
                    VCare.get().setupSessionCookie(apiStr, apiStr, user, userStr);
                    AssistInfo assistInfo = new AssistInfo();  //AssistInfo存入share内容为手机号作为登录名
                    assistInfo.setMobile(info.getMobile());
                    //友盟推送初始化
                    if (!TextUtils.isEmpty(UmengUtils.getdeviceToken())) {
                        setUmtoken(UmengUtils.getdeviceToken());
                    }
                    CrashReport.setUserId("facebook:" + user.getId());
                    SpAssist.setAssistInfo(assistInfo);
                    XMPPCenter.loginChat();
                } else {

                }
                int codeId = Codes.NET_SIGN_LOGIN;
                switch (name) {
                    case SignActvts.REG:
                        codeId = Codes.NET_SIGN_LOGIN_REGISTER;
                        break;
                    case SignActvts.LOGIN:
                        codeId = Codes.NET_SIGN_LOGIN;
                        break;
                }
                EventBus.getDefault().post(new MainEvent(codeId, ret, msg));
            }
        }));
        return false;
    }

    public static boolean getFPwdCap(String mobile, final int name) {
        if (DataCenter.noNet()) {
            return false;
        }
        mobile += mobile + "proton521";
        List params = new ArrayList();
        params.add(new ParamPair(Extras.MOBILE, encrypt(mobile, Settings.ENCRYPT_KEY)));
        VolleyUtil.addRequest(new JPost(getApi(getFpwdCap), params, new Response.Listener<ResultPair>() {
            @Override
            public void onResponse(ResultPair response) {
                String ret = response.getName();
                String msg = response.getValue();
                int codeId = Codes.NET_SIGN_FPWD_GET_CAP;
                EventBus.getDefault().post(new MainEvent(codeId, ret, msg));
            }
        }));
        return false;
    }

    /**
     * 验证码验证接口
     *
     * @param mobile 手机号码
     * @param cap    验证码
     */
    public static boolean valiFPwdCap(String mobile, String cap) {
        if (DataCenter.noNet()) {
            return false;
        }
        List params = new ArrayList();
        params.add(new ParamPair(Extras.MOBILE, mobile));
        params.add(new ParamPair(Extras.CAP, cap));
        VolleyUtil.addRequest(new JPost(getApi(valiFpwdCap), params, new Response.Listener<ResultPair>() {
            @Override
            public void onResponse(ResultPair response) {
                String ret = response.getName();
                String msg = response.getValue();
                LogUtils.e(response);
                EventBus.getDefault().post(new MainEvent(Codes.NET_SIGN_FPWD_VALI_CAP, ret, msg));
            }
        }));
        return false;
    }


    public static boolean changePwd(RegisterInfo info) {
        if (DataCenter.noNet()) {
            return false;
        }
        List params = new ArrayList();
        params.add(new ParamPair(Extras.MOBILE, info.getMobile()));
        params.add(new ParamPair(Extras.PWD, md5(info.getPwd())));
        params.add(new ParamPair(Extras.CODE, info.getCode()));
        params.add(new ParamPair(Extras.NEWPWD, md5(info.getPwd())));
        VolleyUtil.addRequest(new JPost(getApi(changeFpwd), params, new Response.Listener<ResultPair>() {
            @Override
            public void onResponse(ResultPair response) {
                String ret = response.getName();
                String msg = response.getValue();

                EventBus.getDefault().post(new MainEvent(Codes.NET_SIGN_FPWD_CHNAGE, ret, msg));
            }
        }));
        return false;
    }

    public static boolean getRegisterCap(String mobile) {
        if (DataCenter.noNet()) {
            return false;
        }

        mobile += mobile + "proton521";

        List params = new ArrayList();
        params.add(new ParamPair(Extras.MOBILE, encrypt(mobile, Settings.ENCRYPT_KEY)));
        VolleyUtil.addRequest(new JPost(getApi(getRegCap), params, new Response.Listener<ResultPair>() {
            @Override
            public void onResponse(ResultPair response) {
                String ret = response.getName();
                String msg = response.getValue();
                LogUtils.e(ret + msg);
                EventBus.getDefault().post(new MainEvent(Codes.NET_SIGN_REGISTER_GET_CAP, ret, msg));
            }
        }));
        return false;
    }

    public static boolean valiRegCap(String mobile, String cap) {
        if (DataCenter.noNet()) {
            return false;
        }
        List params = new ArrayList();
        params.add(new ParamPair(Extras.MOBILE, mobile));
        params.add(new ParamPair(Extras.CAP, cap));
        VolleyUtil.addRequest(new JPost(getApi(valiRegCap), params, new Response.Listener<ResultPair>() {
            @Override
            public void onResponse(ResultPair response) {
                String ret = response.getName();
                String msg = response.getValue();
                EventBus.getDefault().post(new MainEvent(Codes.NET_SIGN_REGISTER_VALI_CAP, ret, msg));
            }
        }));
        return false;
    }

    public static boolean register(RegisterInfo registerInfo) {
        if (DataCenter.noNet()) {
            return false;
        }
        List params = new ArrayList();
        params.add(new ParamPair(Extras.TYPE, registerInfo.getType()));
        params.add(new ParamPair(Extras.MOBILE, registerInfo.getMobile()));
        params.add(new ParamPair(Extras.PWD, md5(registerInfo.getPwd())));
        params.add(new ParamPair(Extras.CODE, registerInfo.getCode()));
        VolleyUtil.addRequest(new JPost(getApi(register), params, new Response.Listener<ResultPair>() {
            @Override
            public void onResponse(ResultPair response) {
                String ret = response.getName();
                String msg = response.getValue();
                EventBus.getDefault().post(new MainEvent(Codes.NET_SIGN_REGISTER, ret, msg));
            }
        }));
        return false;
    }


    public static boolean setUmtoken(String umtoken) {
        if (DataCenter.noNet()) {
            return false;
        }
        List params = new ArrayList();
        params.add(new ParamPair(Extras.UMTOKEN, umtoken));
        VolleyUtil.addRequest(new JPost(getApi(setumtoken), params, new Response.Listener<ResultPair>() {
            @Override
            public void onResponse(ResultPair response) {
                String ret = response.getName();
                String ms = response.getValue();
                if (isSuccess(ret)) {
                    LogUtils.d("update umtoken is success");

                } else {
                    LogUtils.e("update umtoken is fail： " + ms);
                }
                LogUtils.e(response);
            }
        }));
        return false;
    }

    public static String encrypt(String input, String key) {
//        return input;
        byte[] crypted = null;

        try {
            SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skey);
            crypted = cipher.doFinal(input.getBytes("UTF-8"));
            System.out.println(crypted);
        } catch (Exception e) {
            LogUtils.e(e.getMessage());
        }
        return new String(Base64.encodeBase64(crypted));
    }

    public static String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result.toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

}
